import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import weixinShare from '../../lib/weixinShare';
import { addErrorListener } from '../../lib/handleError';
import AJAX from '../../lib/ajax';
import weui from 'weui.js';
import Area from '../../lib/area'

import checkSubmit from './checkSubmit';

require('../../lib/rem');
require('../../styles/common.less');
require('./SenderInfo.less');
require('../../styles/iconfont/iconfont.css');

class SenderInfo extends Component {
  constructor(props) {
    super(props)
    this.senderInfo = {};

    if (sessionStorage.getItem('senderInfo')) { // 本地读取缓存信息
      this.senderInfo = sessionStorage.getItem('senderInfo').replace(/\s*/g, "").split('#')

      let i = 2
      while (i <= 4) {
        this.senderInfo[i] = JSON.parse(this.senderInfo[i])
        i++
      }
    }

    this.state = {
      isReady: false,     //是否可以加载页面
      addressIsNull: true,
      name: this.senderInfo[0] || '',
      phone: this.senderInfo[1] || '',
      defaultProvince: [],
      defaultCity: [],
      defaultCounty: [],
      address: '',
      selectArea: this.senderInfo.length > 4 ? {} : {color: '#999'}, // 是否选择了省市区
    };
  }

  componentWillMount() {
    addErrorListener()()
    weixinShare.hideAll()
  }

  componentDidMount() {
    AJAX.appendBaiduAnalysis()

    this.fetchArea()
  }

  fetchArea() {
    Area(res => {
      const area = res;
      this.area = res;

      this.setState({
        defaultProvince: this.senderInfo[2] || // 默认省
          [
            area[0].value,
            '请选择省市区'
          ],
        defaultCity: this.senderInfo[3] || // 默认市
          [
            area[0].children[0].value,
            ''
          ],
        defaultCounty: this.senderInfo[4] || // 默认区县
          [
            area[0].children[0].children[0].value,
            ''
          ],
        address: this.senderInfo[5] || '',
        selectArea: this.senderInfo.length > 4 ? {} : {color: '#999'},
        isReady: true, //是否可以加载页面
      })
    });
  }

  selectAddress() {
    weui.picker(this.area,{
        className: 'custom-classname',

        container: 'body',

        defaultValue: [
          this.state.defaultProvince[0],
          this.state.defaultCity[0],
          this.state.defaultCounty[0]
        ],

        onConfirm: (result) => {
          this.setState({
            defaultProvince: [
              result[0].value,
              result[0].label
            ],

            defaultCity: [
              result[1].value,
              result[1].label
            ],

            defaultCounty: [
              result[2].value,
              result[2].label
            ],
            selectArea: {}
          })
        },
        title: '请选择省市区'
      }
    )
  }

  handleSubmit () { // 提交
    const nullProvince = !this.state.defaultProvince[1] || (this.state.defaultProvince[1] == '请选择省市区');
    const nullCity = !this.state.defaultCity[1];
    const nullCuonty = !this.state.defaultCounty[1];

    if (nullProvince || nullCity || nullCuonty) {
      weui.topTips('请选择省市区');
      return;
    }

    const name = this.refs.name.value
    const phone = this.refs.phone.value
    const address = this.refs.address.value

    const returnRes = checkSubmit(name, phone, address)
    switch (returnRes[0]) {
      case 0:
        weui.topTips(returnRes[1]);
        return;
      case 1:
        const senderInfo = `
        ${name}#
        ${phone}#
        ${JSON.stringify(this.state.defaultProvince)}#
        ${JSON.stringify(this.state.defaultCity)}#
        ${JSON.stringify(this.state.defaultCounty)}#
        ${address}
      `
        sessionStorage.setItem('senderInfo', senderInfo)
        location.href = "/SendExpress"
        return;
    }
  }

  addressFocus () { // 地址获取焦点
    this.setState({
      addressIsNull: this.refs.address.value ? false : true
    })
  }

  addressBlur () { // 地址失去焦点
    setTimeout(() => { // 防止失去焦点无法点击清除按钮
      this.setState({
        addressIsNull: true
      })
    }, 10)
    window.scroll(0, 0);
  }

  changeAddress () { // 改变地址输入时
    const address = this.refs.address.value;
    let addressNull = address ? false : true;

    this.setState({
      addressIsNull: addressNull
    })
  }

  handleClear () { // 清空输入
    this.refs.address.value = null
    this.refs.address.focus()
  }


  render () {
    return (
      this.state.isReady &&
      <div className="senderInfo">
        <section className="card senderTitle">
          <span>寄</span>
          <label>寄件人信息</label>
        </section>

        <section className="card senderEdit">
          <ul>
            <li>
              <input type="text" ref="name"
                defaultValue={this.state.name}
                className="nameEdit"
                placeholder="姓名"
              />

              <input type="number" ref="phone"
                defaultValue={this.state.phone}
                className="phoneEdit"
                placeholder="电话"
              />
            </li>

            <li onClick={this.selectAddress.bind(this)}>
              <labe style={this.state.selectArea}>{this.state.defaultProvince[1]} {this.state.defaultCity[1]} {this.state.defaultCounty[1]}</labe>
              <span className="icon iconfont iconIcon_right"></span>
            </li>

            <li>
              <input type="text" className="addressEdit"
                defaultValue={this.state.address}
                ref="address"
                onFocus={this.addressFocus.bind(this)}
                onBlur={this.addressBlur.bind(this)}
                onChange={this.changeAddress.bind(this)}
                placeholder="请填写详细地址（街道名称楼栋号门牌号等）"
              />
              {
                !this.state.addressIsNull
                ?
                <em className="icon iconfont iconIcon_error"
                  onClick={this.handleClear.bind(this)}
                ></em>
                :
                null 
              }
            </li>
          </ul>

          <button type="button"
            className="submitBtn"
            onClick={this.handleSubmit.bind(this)}
          >确定
          </button>
        </section>
      </div>
    )
  }
}
ReactDOM.render(<SenderInfo />, document.getElementById('app'));
if (module.hot) {
  module.hot.accept();
}

